<?php

class OhvuiController extends Zend_Controller_Action {

    const BASE_URL = "http://www.ovui.vn/";
    const LEGEND_MODULE_BASE_URL = "http://www.ovui.vn/legend/"; // http://www.ovui.vn/legend/1
    const HOT_MODULE_BASE_URL = "http://www.ovui.vn/hot/";
    const NEW_MODULE_BASE_URL = "http://www.ovui.vn/new/";
    const VOTE_MODULE_BASE_URL = "http://www.ovui.vn/vote/";
    const METHOD_LEGEND = "legend";
    const METHOD_HOT = "hot";
    const METHOD_NEW = "new";
    const METHOD_VOTE = "vote";

    private function getBaseUrl($method) {
        switch ($method) {
            case static::METHOD_LEGEND:
                return static::LEGEND_MODULE_BASE_URL;
                break;
            case static::METHOD_HOT:
                return static::HOT_MODULE_BASE_URL;
                break;
            case static::METHOD_NEW:
                return static::NEW_MODULE_BASE_URL;
                break;
            case static::METHOD_VOTE:
                return static::VOTE_MODULE_BASE_URL;
                break;
            default:
                break;
        }
    }

    private static $memcache;
    private static $query_cache;

    public function __construct(\Zend_Controller_Request_Abstract $request, \Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
        parent::__construct($request, $response, $invokeArgs);

        /*$frontendoptions = array(
            'lifetime' => 60 * 15, // 5minutes
            'automatic_serialization' => true
        );
        $backendoptions = array(
            'cache_dir' => sys_get_temp_dir(),
            'file_name_prefix' => 'zend_cache_query_ohvui',
            'hashed_directory_level' => 2
        );
        self::$query_cache = Zend_Cache::factory('Core', 'File', $frontendoptions, $backendoptions);

        if (Haibl_ConfigData::SUPPORT_MEMCACHED) {
            self::$memcache = new Memcache;
            self::$memcache->connect(Haibl_ConfigData::DOMAIN, Haibl_ConfigData::PORT) or die("Could not connect");
        }*/
    }

    public function getAccessMemcachedKey() {
        $params = $this->_request->getParams();
        $requestParams = '';
        foreach ($params as $key => $value) {
            if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                $requestParams.= $key . '=' . $value;
            }
        }
        $action = $this->_request->getActionName();
        return md5($action . $requestParams);
    }

    public function checkAccessKeyParams() {
        $page = $this->_request->getParam("page");
        $appid = $this->_request->getParam("key");
        $sig = $this->_request->getParam("sig");
        $method = $this->_request->getParam("method");
        if ($appid == "" || $sig == "" || $page == "" || $method == "") {
            echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$INVAILD_PARAMS);
            return false;
        } else {
            if ($appid != Haibl_ConfigData::KEY) {
                echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                return false;
            } else {
                $params = $this->_request->getParams();
                $requestParams = '';
                foreach ($params as $key => $value) {
                    if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                        $requestParams.= $key . '=' . $value;
                    }
                }
                $requestParams.= Haibl_ConfigData::ACCESS_KEY;
                $encryptParams = md5($requestParams);

                if ($encryptParams == $sig) {
                    return true;
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                    if (Haibl_ConfigData::DEBUG) {
                        echo "<p>encryptParams = " . $encryptParams . "</p>";
                    }
                    return false;
                }
            }
        }
    }

    public function indexAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $isAccess = $this->checkAccessKeyParams();
        if ($isAccess) {

            $method = $this->_request->getParam("method") == "" ? "" : $this->_request->getParam("method");
            $page = $this->_request->getParam("page") == "" ? 1 : $this->_request->getParam("page");

            $key = $this->getAccessMemcachedKey();
            $memCachedData = null;
            if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                self::$memcache->get($key);

            if ($memCachedData != null) {
                echo json_encode($memCachedData);
            } else {
                $lists = null;

                $baseUrl = $this->getBaseUrl($method);
                if ($baseUrl != "") {
                    $baseUrl .= $page;
                    $lists = $this->getImageLists($baseUrl);
                }
                $returnData = array();
                if ($lists != null && !empty($lists)) {
                    $returnData['errorId'] = Sunny_ErrorHandled::$DONE;
                    $returnData['data'] = $lists;
                    if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                        self::$memcache->set($key, $returnData, false, Haibl_ConfigData::CACHED_KEEP_ALIVE) or die("Failed to save data at the server");
                    echo json_encode($returnData);
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$PAGE_NOT_FOUND);
                }
            }
        }
    }

    function getImageLists($baseUrl) {
        $key = $this->getAccessMemcachedKey();
        if (true) {
            $client = new Zend_Http_Client();
            $client->setUri($baseUrl);
            $response = $client->request();
            $html = $response->getBody();

            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.list');

            $data = array();
            $dataIndex = 0;

            $results->rewind();
            $domDoc = $results->current();
            $DOMNodeList = $domDoc->getElementsByTagName("li");
            $length = $DOMNodeList->length;
            for ($index = 0; $index < $length; $index++) {
                $liTag = $DOMNodeList->item($index);
                if ($liTag->getAttribute("class") == " gag-link") {

                    $aTag = $liTag->getElementsByTagName("a");
                    if ($aTag->length > 0) {
                        $aTag = $aTag->item(0);
                        $data[$dataIndex]['img'] = $aTag->getAttribute("href");

                        $img = $aTag->getElementsByTagName("img");
                        if ($img->length > 0) {
                            $img = $img->item(0);
                            $data[$dataIndex]['src'] = $img->getAttribute("src");
                            $src = $data[$dataIndex]['src'];

                            $data[$dataIndex]['title'] = $img->getAttribute("alt");
                            $data[$dataIndex]['uploader'] = "";

                            $imgLink = $data[$dataIndex]['src'];
                            if (strrpos($imgLink, Haibl_ConfigData::YOU_TUBE)) {
                                $data[$dataIndex]['video'] = "1";
                            } else {
                                $data[$dataIndex]['video'] = "0";

                                $src = $data[$dataIndex]['src'];
                                $src = str_replace("http://", "", $src);

                                $pieces = explode("/", $src);
                                $count = count($pieces);
                                if ($count > 1) {
                                    $imageName = "l-" . $pieces[$count - 1];
                                    $bigsrc = "http://";
                                    for ($i = 0; $i < $count - 1; $i++) {
                                        $bigsrc.=$pieces[$i] . "/";
                                    }
                                    $bigsrc.=$imageName;
                                    $data[$dataIndex]['bigsrc'] = $bigsrc;
                                }
                            }

                            if ($data[$dataIndex]['video'] == "1") {
                                $pieces = explode("/", $imgLink);
                                $count = count($pieces);
                                if ($count > 2) {
                                    $proxy = $pieces[$count - 2];
                                    $data[$dataIndex]['videoLink'] = "http://www.youtube.com/embed/" . $proxy;
                                }
                            }
                        }
                    }

                    $divChildTag = $liTag->getElementsByTagName("div");
                    for ($i = 0; $i < $divChildTag->length; $i++) {
                        $child = $divChildTag->item($i);
                        if ($child->getAttribute("class") == "info scriptolution-stop") {

                            $a = $child->getElementsByTagName("a");
                            if ($a->length > 0) {
                                if ($data[$dataIndex]['title'] == "") {
                                    $data[$dataIndex]['title'] = $a->item(0)->nodeValue;
                                }
                                if ($data[$dataIndex]['uploader'] == "") {
                                    $data[$dataIndex]['uploader'] = $a->item(1)->nodeValue;
                                }
                            }
                            $p = $child->getElementsByTagName("p");
                            if ($p->length > 0) {
                                $data[$dataIndex]['postime'] = $p->item(0)->nodeValue;
                            }
                            $span = $child->getElementsByTagName("span");
                            if ($span->length > 3) {

                                //0 view
                                $data[$dataIndex]['view'] = $spanChild = $span->item(0)->nodeValue;
                                //2 comment
                                $data[$dataIndex]['comment'] = $spanChild = $span->item(2)->nodeValue;
                                //3 like
                                $data[$dataIndex]['like'] = $spanChild = $span->item(3)->nodeValue;
                            }
                        }
                    }
                    $dataIndex++;
                }
            }
            //self::$query_cache->save($data, $key);
            return $data;
        } else {
            return $result;
        }
    }

}
?>

